<?php

namespace App\Http\Controllers\Api;

use App\Course;
use App\CourseSignup;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Carbon\Carbon;


class CourseController extends Controller
{
    public function index()
    {
        $courses = Course::all();
        $filter = collect();
        foreach ($courses as $key ) {
            if($key->status == 1)
                $filter->push($key);
        }
        return [
            'status' => 'success',
            'data_size' => $filter->count(),
            'data' => $filter
        ];
    }

    public function detail($id)
    {
        return [
            'status' => 'success',
            'data' => [
                'course' =>Course::find($id),
                'coach' => Course::find($id)->coach,
                'admin' => Course::find($id)->admin
            ]
        ];
    }

    public function signup($id)
    {
        $signup = CourseSignup::create([
            'signup_time' => now(),
            'user_id' => 2,
            'courses_id' => $id,
            'status' => 0
        ]);

        return [
            'status' => 'success',
            'data' => [
                'course_signup_id' => $signup->id,
                'signup_time' => $signup->signup_time
            ]
        ];
    }

    public function signuplist($id)
    {
        $signlist = Course::find($id)->signlist;
        foreach ($signlist as $item ) {
            $user = User::find($item->user_id);
            $item->course = Course::find($item->courses_id)->title;
            $item->user = [
                'username'=> $user->username,
                'age' => Carbon::parse($user->birthdate)->diffInYears(),
                'gender' => $user->gender
            ];
        }
        return [
            'status' => 'success',
            'data_size' => $signlist->count(),
            'data' => $signlist
        ];
    }
}
